import React, { useState, useEffect } from 'react';
import { Card, Button, message, Spin, Select, Space } from 'antd';
import { ReloadOutlined, FilterOutlined } from '@ant-design/icons';
import ApiOverviewCards from './ApiOverviewCards';
import ApiFilterBar from './ApiFilterBar';
import ApiTable from './ApiTable';
import { fetchMethodPageQuery } from '../../../services/method';
import { fetchApiOverviewStatisticsWithPeriod, ApiOverviewStatisticsDTO } from '../../../services/statistics';

const { Option } = Select;

interface ApiAnalysisTabProps {
    unitId: string;
}

interface ApiFilterParams {
    periodMonths?: number;
    callFrequencyCategory?: string;
    serviceType?: string;
    hasApmRecord?: boolean | string;
    hasSaRecord?: boolean | string;
    deprecationLevel?: string;
    packageName?: string;
    className?: string;
    methodName?: string;
    serviceName?: string;
    noSaCallDurationDays?: number;
    noCodeChangeDurationDays?: number;
    orderBy?: string;
    orderByType?: string;
    [key: string]: any; // 允许其他动态属性
}

const ApiAnalysisTab: React.FC<ApiAnalysisTabProps> = ({ unitId }) => {
    const [loading, setLoading] = useState(false);
    const [statisticsLoading, setStatisticsLoading] = useState(false);
    const [tableData, setTableData] = useState<any>({ records: [], total: 0 });
    const [statisticsData, setStatisticsData] = useState<ApiOverviewStatisticsDTO>({
        totalApiCount: 0,
        restApiCount: 0,
        dubboApiCount: 0,
        highFreqApiCount: 0,
        mediumFreqApiCount: 0,
        lowFreqApiCount: 0,
        noCallApiCount: 0
    });
    const [filterParams, setFilterParams] = useState<ApiFilterParams>({});
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0
    });

    // 构建查询参数
    const buildQueryParams = (page: number = 1, pageSize: number = 10, filters: any = {}) => {
        const query: any = {
            unitId: unitId,
            isEntry: true, // 固定筛选入口方法
            pageNum: page,
            pageSize: pageSize
        };

        // 复制所有筛选条件到查询参数
        // 包括：serviceType, callFrequencyCategory, hasApmRecord, hasSaRecord, deprecationLevel 等
        Object.keys(filters).forEach(key => {
            // 跳过特殊字段
            if (key === 'periodMonths' || key === 'quickSort' || key === '_isQuickSearch') {
                return;
            }

            // 处理布尔值字符串
            if (key === 'hasApmRecord' || key === 'hasSaRecord') {
                if (filters[key] === 'true') {
                    query[key] = true;
                } else if (filters[key] === 'false') {
                    query[key] = false;
                }
            } else {
                query[key] = filters[key];
            }
        });

        // 周期筛选 - 根据创建时间
        if (filters.periodMonths) {
            const cutoffDate = new Date();
            cutoffDate.setMonth(cutoffDate.getMonth() - filters.periodMonths);
            // 设置为当天的开始时间
            cutoffDate.setHours(0, 0, 0, 0);
            query.createTimeAfter = cutoffDate.toISOString(); // 使用ISO格式
        }

        // 过滤掉空值
        Object.keys(query).forEach(key => {
            if (query[key] === undefined || query[key] === null || query[key] === '') {
                delete query[key];
            }
        });

        console.log('[ApiAnalysisTab] 构建的查询参数:', query);
        return query;
    };

    // 加载统计数据
    const loadStatisticsData = async (filters: ApiFilterParams = filterParams) => {
        if (!unitId) {
            message.warning('单元ID不能为空');
            return;
        }

        setStatisticsLoading(true);
        try {
            // 构建时间参数
            let createTimeAfter: string | undefined;
            if (filters.periodMonths) {
                const cutoffDate = new Date();
                cutoffDate.setMonth(cutoffDate.getMonth() - filters.periodMonths);
                cutoffDate.setHours(0, 0, 0, 0);
                createTimeAfter = cutoffDate.toISOString();
            }

            const response = await fetchApiOverviewStatisticsWithPeriod(unitId, createTimeAfter);

            if (response && ((response as any).code === 0 || !(response as any).code)) {
                const data = (response as any).data || response;
                setStatisticsData({
                    totalApiCount: data.totalApiCount || 0,
                    restApiCount: data.restApiCount || 0,
                    dubboApiCount: data.dubboApiCount || 0,
                    highFreqApiCount: data.highFreqApiCount || 0,
                    mediumFreqApiCount: data.mediumFreqApiCount || 0,
                    lowFreqApiCount: data.lowFreqApiCount || 0,
                    noCallApiCount: data.noCallApiCount || 0
                });
            } else {
                const errorMsg = (response as any).msg || (response as any).message || '请求失败';
                message.error('加载统计数据失败: ' + errorMsg);
            }
        } catch (error) {
            console.error('加载统计数据失败:', error);
            message.error('加载统计数据失败，请稍后重试');
        } finally {
            setStatisticsLoading(false);
        }
    };

    // 加载API数据
    const loadApiData = async (page: number = 1, pageSize: number = 10, filters: ApiFilterParams = filterParams) => {
        if (!unitId) {
            message.warning('单元ID不能为空');
            return;
        }

        setLoading(true);
        try {
            const queryParams = buildQueryParams(page, pageSize, filters);
            const response = await fetchMethodPageQuery(queryParams);

            if (response.code === 0) {
                setTableData({
                    records: response.data.records || [],
                    total: response.data.total || 0
                });
                setPagination(prev => ({
                    ...prev,
                    current: page,
                    pageSize: pageSize,
                    total: response.data.total || 0
                }));
            } else {
                const errorMsg = response.msg || response.message || '请求失败';
                message.error('加载API数据失败: ' + errorMsg);
            }
        } catch (error) {
            console.error('加载API数据失败:', error);
            message.error('加载API数据失败，请稍后重试');
        } finally {
            setLoading(false);
        }
    };

    // 页面初始化时加载数据
    useEffect(() => {
        if (unitId) {
            loadApiData();
            loadStatisticsData();
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [unitId]);

    // 处理筛选条件变化
    const handleFilterChange = (newFilters: ApiFilterParams) => {
        setFilterParams(newFilters);
        loadApiData(1, pagination.pageSize, newFilters);
        loadStatisticsData(newFilters);
    };

    // 处理表格分页变化
    const handleTableChange = (page: number, pageSize: number) => {
        loadApiData(page, pageSize, filterParams);
    };

    // 手动刷新数据
    const handleRefresh = () => {
        loadApiData(pagination.current, pagination.pageSize, filterParams);
        loadStatisticsData(filterParams);
    };

    // 获取周期文本
    const getPeriodText = (periodMonths?: number): string => {
        if (periodMonths === 6) return '近半年';
        if (periodMonths === 12) return '近一年';
        return '';
    };

    return (
        <div style={{ padding: '0 24px' }}>
            <Spin spinning={loading} tip="正在加载API数据..." size="large">
                <div>
                    {/* API概览卡片 - 暂时隐藏 */}
                    {/* <ApiOverviewCards
                        data={statisticsData}
                        loading={statisticsLoading}
                        periodText={getPeriodText(filterParams.periodMonths)}
                    /> */}

                    {/* 筛选栏 */}
                    <Card
                        size="small"
                        style={{
                            marginBottom: '16px',
                            borderRadius: '8px',
                            boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
                        }}
                    >
                        <ApiFilterBar
                            onFilterChange={handleFilterChange}
                            loading={loading}
                        />
                    </Card>

                    {/* API表格 */}
                    <ApiTable
                        data={tableData.records}
                        pagination={pagination}
                        loading={loading}
                        onChange={handleTableChange}
                        unitInfo={{ unitId }}
                    />
                </div>
            </Spin>
        </div>
    );
};

export default ApiAnalysisTab;